package ls.ch01.demo8;

import java.lang.reflect.Field;

/**
 * @author ls
 * @Date 创建时间:2022/4/4 19:12
 * 描述:
 */

public class Demo8 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        //通过反射加载一个Person实例
        Class clz = Class.forName("com.ls.ch01.demo1.Person");
        Object person = clz.newInstance();

        //获取private String name 属性
        Field name = clz.getDeclaredField("name");
        //name属性为private，这里已超出其访问范围，不能直接访问
        //通过setAccessable方法，设定为可以访问
        name.setAccessible(true);
        //先取值看一下
        System.out.println("赋值前的name:" + name.get(person));
        //为name属性赋值
        name.set(person, "New Person");
        //展示赋值效果
        System.out.println("赋值后的name:" + name.get(person));
    }
}
